package com.chouxiaozi.wechatpublic.commons.util;


import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * json常用静态方法
 */
@SuppressWarnings("unchecked")
public class JsonUtil {

	private static ObjectMapper objectMapper = new ObjectMapper();
	/**
	 * 把对象转成json格式，放到response输出流中
	 * @param response
	 * @param object
	 * @throws Exception 
	 */
	public static String writeJson(Object object) {
		if(object==null) return null;
		try {
			return objectMapper.writeValueAsString(object);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	/**
	 * 读取json，转化为java对象,其中key：value，value的值不能为null，可以用""替换
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	public static Object readJson(String jsonString,Class clazz) {
		try {
			if(jsonString==null || "".equals(jsonString)){
				return null;
			}
			return (Object)objectMapper.readValue(jsonString, clazz);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
}
